{{define "title"}}
Wireguard Clients
{{end}}

{{define "top_css"}}
<style>
    .paused-client {
        transition: transform .2s;
        cursor: pointer;
    }
    i[class^="paused-client"]:hover { transform: scale(1.5); }
</style>
{{end}}

{{define "username"}}
{{ .username }}
{{end}}

{{define "page_title"}}
Wireguard Clients
{{end}}

{{define "page_content"}}
<section class="content">
    <div class="container-fluid">
        <!-- <h5 class="mt-4 mb-2">Wireguard Clients</h5> -->
        <div class="row" id="client-list">
        </div>
        <!-- /.row -->
    </div>
</section>

<div class="modal fade" id="modal_email_client">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Email Configuration</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form name="frm_email_client" id="frm_email_client">
                <div class="modal-body">
                    <input type="hidden" id="e_client_id" name="e_client_id">
                    <div class="form-group">
                        <label for="e_client_email" class="control-label">Email address</label>
                        <input type="text" class="form-control" id="e_client_email" name="e_client_email">
                    </div>
                </div>
                <div class="modal-footer justify-content-between">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-success">Send</button>
                </div>
            </form>
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>
<!-- /.modal -->

<div class="modal fade" id="modal_qr_client">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">QR Code</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="qr_client_id" name="qr_client_id">
                <img id="qr_code" class="w-100" style="image-rendering: pixelated;" src="" alt="QR code" />
                <!-- do not include FwMark in any client configs: it is INVALID. -->
            </div>
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>
<!-- /.modal -->

<div class="modal fade" id="modal_telegram_client">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Telegram Configuration</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form name="frm_telegram_client" id="frm_telegram_client">
                <div class="modal-body">
                    <input type="hidden" id="tg_client_id" name="tg_client_id">
                    <div class="form-group">
                        <label for="tg_client_userid" class="control-label">Telegram userid</label>
                        <input type="text" class="form-control" id="tg_client_userid" name="tg_client_userid">
                    </div>
                </div>
                <div class="modal-footer justify-content-between">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-success">Send</button>
                </div>
            </form>
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>
<!-- /.modal -->

<div class="modal fade" id="modal_edit_client">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Edit Client</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form name="frm_edit_client" id="frm_edit_client">
                <div class="modal-body">
                    <input type="hidden" id="_client_id" name="_client_id">
                    <div class="form-group">
                        <label for="_client_name" class="control-label">Name</label>
                        <input type="text" class="form-control" id="_client_name" name="_client_name">
                    </div>
                    <div class="form-group">
                        <label for="_client_email" class="control-label">Email</label>
                        <input type="text" class="form-control" id="_client_email" name="client_email">
                    </div>
                    <div class="form-group">
                        <label for="_subnet_ranges" class="control-label">Subnet range</label>
                        <select id="_subnet_ranges" class="select2"
                            data-placeholder="Select a subnet range" style="width: 100%;">
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="_client_allocated_ips" class="control-label">IP Allocation</label>
                        <input type="text" data-role="tagsinput" class="form-control" id="_client_allocated_ips">
                    </div>
                    <div class="form-group">
                        <label for="_client_allowed_ips" class="control-label">Allowed IPs</label>
                        <input type="text" data-role="tagsinput" class="form-control" id="_client_allowed_ips">
                    </div>
                    <div class="form-group">
                        <label for="_client_extra_allowed_ips" class="control-label">Extra Allowed IPs</label>
                        <input type="text" data-role="tagsinput" class="form-control"
                               id="_client_extra_allowed_ips">
                    </div>
                    <div class="form-group">
                        <label for="_client_endpoint" class="control-label">Endpoint</label>
                        <input type="text" class="form-control" id="_client_endpoint" name="client_endpoint">
                    </div>
                    <div class="form-group">
                        <div class="icheck-primary d-inline">
                            <input type="checkbox" id="_use_server_dns">
                            <label for="_use_server_dns">
                                Use server DNS
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="icheck-primary d-inline">
                            <input type="checkbox" id="_enabled">
                            <label for="_enabled">
                                Enable this client
                            </label>
                        </div>
                    </div>
                    <details>
                        <summary><strong>Public and Preshared Keys</strong>
                            <i class="fas fa-info-circle" data-toggle="tooltip"
                               data-original-title="Update the server stored
                               client Public and Preshared keys.">
                            </i>
                        </summary>
                        <div class="form-group" style="margin-top: 1rem">
                            <label for="_client_public_key" class="control-label">
                                Public Key
                            </label>
                            <input type="text" class="form-control" id="_client_public_key" name="_client_public_key" aria-invalid="false">
                        </div>
                        <div class="form-group">
                            <label for="_client_preshared_key" class="control-label">
                                Preshared Key
                            </label>
                            <input type="text" class="form-control" id="_client_preshared_key" name="_client_preshared_key">
                        </div>
                    </details>
                    <details style="margin-top: 0.5rem;">
                        <summary><strong>Additional configuration</strong>
                        </summary>
                        <div class="form-group" style="margin-top: 0.5rem;">
                            <label for="_client_telegram_userid" class="control-label">Telegram userid</label>
                            <input type="text" class="form-control" id="_client_telegram_userid" name="_client_telegram_userid">
                        </div>
                        <div class="form-group">
                            <label for="_additional_notes" class="control-label">Notes</label>
                            <textarea class="form-control" style="min-height: 6rem;" id="_additional_notes" name="_additional_notes" placeholder="Additional notes about this client"></textarea>
                        </div>
                    </details>
                </div>
                <div class="modal-footer justify-content-between">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-success">Save</button>
                </div>
            </form>
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>
<!-- /.modal -->

<div class="modal fade" id="modal_pause_client">
    <div class="modal-dialog">
        <div class="modal-content bg-warning">
            <div class="modal-header">
                <h4 class="modal-title">Disable</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
            </div>
            <div class="modal-footer justify-content-between">
                <button type="button" class="btn btn-outline-dark" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-outline-dark" id="pause_client_confirm">Apply</button>
            </div>
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>
<!-- /.modal -->

<div class="modal fade" id="modal_remove_client">
    <div class="modal-dialog">
        <div class="modal-content bg-danger">
            <div class="modal-header">
                <h4 class="modal-title">Remove</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
            </div>
            <div class="modal-footer justify-content-between">
                <button type="button" class="btn btn-outline-dark" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-outline-dark" id="remove_client_confirm">Apply</button>
            </div>
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>
<!-- /.modal -->
{{end}}

{{define "bottom_js"}}
    <script>
        function populateClientList() {
            $.ajax({
                cache: false,
                method: 'GET',
                url: '{{.basePath}}/api/clients',
                dataType: 'json',
                contentType: "application/json",
                success: function (data) {
                    renderClientList(data);
                },
                error: function (jqXHR, exception) {
                    const responseJson = jQuery.parseJSON(jqXHR.responseText);
                    toastr.error(responseJson['message']);
                }
            });
        }

        function setClientStatus(clientID, status) {
            const data = {"id": clientID, "status": status};
            $.ajax({
                cache: false,
                method: 'POST',
                url: '{{.basePath}}/client/set-status',
                dataType: 'json',
                contentType: "application/json",
                data: JSON.stringify(data),
                success: function (data) {
                    console.log("Set client " + clientID + " status to " + status);
                },
                error: function (jqXHR, exception) {
                    const responseJson = jQuery.parseJSON(jqXHR.responseText);
                    toastr.error(responseJson['message']);
                }
            });
        }

        function resumeClient(clientID) {
            setClientStatus(clientID, true);
            const divElement = document.getElementById("paused_" + clientID);
            divElement.style.visibility = "hidden";
            updateApplyConfigVisibility()
        }

        function pauseClient(clientID) {
            setClientStatus(clientID, false);
            const divElement = document.getElementById("paused_" + clientID);
            divElement.style.visibility = "visible";
            updateApplyConfigVisibility()
        }

        // updateIPAllocationSuggestion function for automatically fill
        // the IP Allocation input with suggested ip addresses
        // FOR CHANGING A SUBNET OF AN EXISTING CLIENT
        function updateIPAllocationSuggestionExisting() {
            let subnetRange = $("#_subnet_ranges").select2('val');

            if (!subnetRange || subnetRange.length === 0) {
                subnetRange = '__default_any__'
            }
            $.ajax({
                cache: false,
                method: 'GET',
                url: `{{.basePath}}/api/suggest-client-ips?sr=${subnetRange}`,
                dataType: 'json',
                contentType: "application/json",
                success: function(data) {
                    const allocated_ips = $("#_client_allocated_ips").val().split(",");
                    allocated_ips.forEach(function (item, index) {
                        $('#_client_allocated_ips').removeTag(escape(item));
                    })
                    data.forEach(function (item, index) {
                        $('#_client_allocated_ips').addTag(item);
                    })
                },
                error: function(jqXHR, exception) {
                    const allocated_ips = $("#_client_allocated_ips").val().split(",");
                    allocated_ips.forEach(function (item, index) {
                        $('#_client_allocated_ips').removeTag(escape(item));
                    })
                    const responseJson = jQuery.parseJSON(jqXHR.responseText);
                    toastr.error(responseJson['message']);
                }
            });
        }

        function updateSubnetRangesList(elementID, preselectedVal) {
            $.getJSON("{{.basePath}}/api/subnet-ranges", null, function(data) {
                $(`${elementID} option`).remove();
                $(elementID).append(
                    $("<option></option>")
                        .text("Any")
                        .val("__default_any__")
                );
                $.each(data, function(index, item) {
                    $(elementID).append(
                        $("<option></option>")
                            .text(item)
                            .val(item)
                    );
                    if (item === preselectedVal) {
                        console.log(preselectedVal);
                        $(elementID).val(preselectedVal).trigger('change')
                    }
                });
            });
        }

        function updateSearchList() {
            $.getJSON("{{.basePath}}/api/subnet-ranges", null, function(data) {
                $("#status-selector option").remove();
                $("#status-selector").append(
                    $("<option></option>")
                        .text("All")
                        .val("All"),
                    $("<option></option>")
                        .text("Enabled")
                        .val("Enabled"),
                    $("<option></option>")
                        .text("Disabled")
                        .val("Disabled"),
                    $("<option></option>")
                        .text("Connected")
                        .val("Connected"),
                    $("<option></option>")
                        .text("Disconnected")
                        .val("Disconnected")
                );
                $.each(data, function(index, item) {
                    $("#status-selector").append(
                        $("<option></option>")
                            .text(item)
                            .val(item)
                    );
                });
            });
        }
    </script>
    <script>
        // load client list
        $(document).ready(function () {
            updateSearchList();
            populateClientList();
        })

        // show search bar and override :contains to be case-insensitive
        $(document).ready(function () {
            $("#search-form").show();
            jQuery.expr[':'].contains = function(a, i, m) {
                return jQuery(a).text().toUpperCase()
                    .indexOf(m[3].toUpperCase()) >= 0;
            };
        })

        // hide all clients and display only the ones that meet the search criteria (name, email, IP)
        $('#search-input').keyup(function () {
            $("#status-selector").val("All");
            let query = $(this).val().trim();
            $('.col-lg-4').hide();
            $(".info-box-text").each(function() {
                if($(this).children('i.fa-user').length > 0 || $(this).children('i.fa-envelope').length > 0)
                {
                    $(this).filter(':contains("' + query + '")').parent().parent().parent().show();
                }
                })
            $(".badge-secondary").filter(':contains("' + query + '")').parent().parent().parent().show();
            $(".fa-tguserid").each(function () {
                if ($(this).parent().text().trim().indexOf(query) != -1) {
                    $(this).closest('.col-lg-4').show();
                }
            })
            let upperQuery = query.toUpperCase()
            $(".fa-additional_notes").each(function () {
                if ($(this).parent().text().trim().indexOf(upperQuery) != -1) {
                    $(this).closest('.col-lg-4').show();
                }
            })
        })

        $("#status-selector").on('change', function () {
            $('#search-input').val("");
            switch ($("#status-selector").val()) {
                case "All":
                    $('.col-lg-4').show();
                    break;
                case "Enabled":
                    $('.col-lg-4').hide();
                    $('[id^="paused_"]').each(function () {
                        if ($(this).css("visibility") === "hidden") {
                            $(this).parent().parent().show();
                        }
                    });
                    break;
                case "Disabled":
                    $('.col-lg-4').hide();
                    $('[id^="paused_"]').each(function () {
                        if ($(this).css("visibility") !== "hidden") {
                            $(this).parent().parent().show();
                        }
                    });
                    break;
                case "Connected":
                    $('.col-lg-4').hide();
                    $.ajax({
                        cache: false,
                        method: 'GET',
                        url: '{{.basePath}}/status',
                        success: function (data) {
                            const returnedHTML = $(data).find(".table-success").get();
                            var returnedString = "";
                            returnedHTML.forEach(entry => returnedString += entry.outerHTML);
                            $(".fa-key").each(function () {
                                if (returnedString.indexOf($(this).parent().text().trim()) != -1) {
                                    $(this).closest('.col-lg-4').show();
                                }
                            })
                        }
                    });
                    break;
                case "Disconnected":
                    $('.col-lg-4').show();
                    $.ajax({
                        cache: false,
                        method: 'GET',
                        url: '{{.basePath}}/status',
                        success: function (data) {
                            const returnedHTML = $(data).find(".table-success").get();
                            var returnedString = "";
                            returnedHTML.forEach(entry => returnedString += entry.outerHTML);
                            $(".fa-key").each(function () {
                                if (returnedString.indexOf($(this).parent().text().trim()) != -1) {
                                    $(this).closest('.col-lg-4').hide();
                                }
                            })
                        }
                    });
                    break;
                default:
                    $('.col-lg-4').hide();
                    const selectedSR = $("#status-selector").val()
                    $(".fa-subnetrange").each(function () {
                        const srs = $(this).parent().text().trim().split(',')
                        for (const sr of srs) {
                            if (sr === selectedSR) {
                                $(this).closest('.col-lg-4').show();
                                break
                            }                            
                        }
                    })
                    // $('.col-lg-4').show();
                    break;
            }
        });

        // modal_pause_client modal event
        $("#modal_pause_client").on('show.bs.modal', function (event) {
            const button = $(event.relatedTarget);
            const client_id = button.data('clientid');
            const client_name = button.data('clientname');
            const modal = $(this);
            modal.find('.modal-body').text("You are about to disable client " + client_name);
            modal.find('#pause_client_confirm').val(client_id);
        })

        // pause_client_confirm button event
        $(document).ready(function () {
            $("#pause_client_confirm").click(function () {
                const client_id = $(this).val();
                pauseClient(client_id);
                $("#modal_pause_client").modal('hide');
            });
        });

        // modal_remove_client modal event
        $("#modal_remove_client").on('show.bs.modal', function (event) {
            const button = $(event.relatedTarget);
            const client_id = button.data('clientid');
            const client_name = button.data('clientname');
            const modal = $(this);
            modal.find('.modal-body').text("You are about to remove client " + client_name);
            modal.find('#remove_client_confirm').val(client_id);
        })

        // remove_client_confirm button event
        $(document).ready(function () {
            $("#remove_client_confirm").click(function () {
                const client_id = $(this).val();
                const data = {"id": client_id};
                $.ajax({
                    cache: false,
                    method: 'POST',
                    url: '{{.basePath}}/remove-client',
                    dataType: 'json',
                    contentType: "application/json",
                    data: JSON.stringify(data),
                    success: function(data) {
                        $("#modal_remove_client").modal('hide');
                        toastr.success('Removed client successfully');
                        const divElement = document.getElementById('client_' + client_id);
                        divElement.style.display = "none";
                        updateApplyConfigVisibility()
                    },
                    error: function(jqXHR, exception) {
                        const responseJson = jQuery.parseJSON(jqXHR.responseText);
                        toastr.error(responseJson['message']);
                    }
                });
            });
        });



        // Edit client modal event
        // This fills the modal dialogue with data from the DB when we open the edit menu
        $(document).ready(function () {
            $("#modal_edit_client").on('show.bs.modal', function (event) {
                let modal = $(this);
                const button = $(event.relatedTarget);
                const client_id = button.data('clientid');

                // IP Allocation tag input
                modal.find("#_client_allocated_ips").tagsInput({
                    'width': '100%',
                    'height': '75%',
                    'interactive': true,
                    'defaultText': 'Add More',
                    'removeWithBackspace': true,
                    'minChars': 0,
                    'minInputWidth': '100%',
                    'placeholderColor': '#666666'
                });

                // AllowedIPs tag input
                modal.find("#_client_allowed_ips").tagsInput({
                    'width': '100%',
                    'height': '75%',
                    'interactive': true,
                    'defaultText': 'Add More',
                    'removeWithBackspace': true,
                    'minChars': 0,
                    'minInputWidth': '100%',
                    'placeholderColor': '#666666'
                });

                modal.find("#_client_extra_allowed_ips").tagsInput({
                    'width': '100%',
                    'height': '75%',
                    'interactive': true,
                    'defaultText': 'Add More',
                    'removeWithBackspace' : true,
                    'minChars': 0,
                    'minInputWidth': '100%',
                    'placeholderColor': '#666666'
                })

                // update client modal data
                $.ajax({
                    cache: false,
                    method: 'GET',
                    url: '{{.basePath}}/api/client/' + client_id,
                    dataType: 'json',
                    contentType: "application/json",
                    success: function (resp) {
                        const client = resp.Client;

                        modal.find(".modal-title").text("Edit Client " + client.name);
                        modal.find("#_client_id").val(client.id);
                        modal.find("#_client_telegram_userid").val(client.telegram_userid);
                        modal.find("#_client_name").val(client.name);
                        modal.find("#_client_email").val(client.email);

                        let preselectedEl
                        if (client.subnet_ranges && client.subnet_ranges.length > 0) {
                            preselectedEl = client.subnet_ranges[0]
                        }

                        updateSubnetRangesList("#_subnet_ranges", preselectedEl);

                        modal.find("#_client_allocated_ips").importTags('');
                        client.allocated_ips.forEach(function (obj) {
                            modal.find("#_client_allocated_ips").addTag(obj);
                        });

                        modal.find("#_client_allowed_ips").importTags('');
                        client.allowed_ips.forEach(function (obj) {
                            modal.find("#_client_allowed_ips").addTag(obj);
                        });

                        modal.find("#_client_extra_allowed_ips").importTags('');
                        client.extra_allowed_ips.forEach(function (obj) {
                            modal.find("#_client_extra_allowed_ips").addTag(obj);
                        });

                        modal.find("#_client_endpoint").val(client.endpoint);

                        modal.find("#_use_server_dns").prop("checked", client.use_server_dns);
                        modal.find("#_enabled").prop("checked", client.enabled);

                        modal.find("#_client_public_key").val(client.public_key);
                        modal.find("#_client_preshared_key").val(client.preshared_key);
                        
                        modal.find("#_additional_notes").val(client.additional_notes);

                        // handle subnet range select
                        $('#_subnet_ranges').on('select2:select', function (e) {
                            updateIPAllocationSuggestionExisting();
                        });
                    },
                    error: function (jqXHR, exception) {
                        const responseJson = jQuery.parseJSON(jqXHR.responseText);
                        toastr.error(responseJson['message']);
                    }
                });
            });
        });

        // regenerateQRCode function for regenerating QR Code adding/removing some parts of configuration because of compatibility issues with some clients
        function regenerateQRCode() {
            const client_id = $("#qr_client_id").val();
            const QRCodeImg = $("#qr_code");
            const QRCodeA = $("#qr_code_a");
            QRCodeImg.hide();
            $.ajax({
                cache: false,
                method: 'GET',
                url: '{{.basePath}}/api/client/' + client_id,
                data: {

                },
                dataType: 'json',
                contentType: "application/json",
                success: function (resp) {
                    const client = resp.Client;

                    $(".modal-title").text("Scan QR Code for " + client.name + " profile");
                    QRCodeImg.attr('src', resp.QRCode).show();
                    QRCodeA.attr('download', resp.Client.name);
                    QRCodeA.attr('href', resp.QRCode).show();
                },
                error: function (jqXHR, exception) {
                    const responseJson = jQuery.parseJSON(jqXHR.responseText);
                    toastr.error(responseJson['message']);
                }
            });
        }

        // submitEmailClient function for sending an email with the configuration to the client
        function submitEmailClient() {
            const client_id = $("#e_client_id").val();
            const email = $("#e_client_email").val();
            const data = {"id": client_id, "email": email};
            $.ajax({
                cache: false,
                method: 'POST',
                url: '{{.basePath}}/email-client',
                dataType: 'json',
                contentType: "application/json",
                data: JSON.stringify(data),
                success: function(resp) {
                    $("#modal_email_client").modal('hide');
                    toastr.success('Sent email to client successfully');
                },
                error: function(jqXHR, exception) {
                    const responseJson = jQuery.parseJSON(jqXHR.responseText);
                    toastr.error(responseJson['message']);
                }
            });
        }

        // submitTelegramClient function for sending a telegram message with the configuration to the client
        function submitTelegramClient() {
            const client_id = $("#tg_client_id").val();
            const userid = $("#tg_client_userid").val();
            const data = {"id": client_id, "userid": userid};
            $.ajax({
                cache: false,
                method: 'POST',
                url: '{{.basePath}}/send-telegram-client',
                dataType: 'json',
                contentType: "application/json",
                data: JSON.stringify(data),
                success: function(resp) {
                    $("#modal_telegram_client").modal('hide');
                    toastr.success('Sent config via telegram to client successfully');
                },
                error: function(jqXHR, exception) {
                    const responseJson = jQuery.parseJSON(jqXHR.responseText);
                    toastr.error(responseJson['message']);
                }
            });
        }

        // submitEditClient function for updating an existing client
        // This sends dialogue data to the back-end when user presses "Save"
        // See e.g. routes.go:UpdateClient for where data is processed/verified.
        function submitEditClient() {
            const client_id = $("#_client_id").val();
            const name = $("#_client_name").val();
            const email = $("#_client_email").val();
            const telegram_userid = $("#_client_telegram_userid").val();
            const allocated_ips = $("#_client_allocated_ips").val().split(",");
            const allowed_ips = $("#_client_allowed_ips").val().split(",");
            let use_server_dns = false;
            let extra_allowed_ips = [];
            const public_key = $("#_client_public_key").val();
            const preshared_key = $("#_client_preshared_key").val();

            if( $("#_client_extra_allowed_ips").val() !== "" ) {
                extra_allowed_ips = $("#_client_extra_allowed_ips").val().split(",");
            }

            const endpoint = $("#_client_endpoint").val();

            if ($("#_use_server_dns").is(':checked')){
                use_server_dns = true;
            }

            let enabled = false;

            if ($("#_enabled").is(':checked')){
                enabled = true;
            }

            const additional_notes = $("#_additional_notes").val();

            const data = {"id": client_id, "name": name, "email": email, "telegram_userid": telegram_userid, "allocated_ips": allocated_ips,
                "allowed_ips": allowed_ips, "extra_allowed_ips": extra_allowed_ips, "endpoint": endpoint,
                "use_server_dns": use_server_dns, "enabled": enabled, "public_key": public_key, "preshared_key": preshared_key, "additional_notes": additional_notes};

            $.ajax({
                cache: false,
                method: 'POST',
                url: '{{.basePath}}/update-client',
                dataType: 'json',
                contentType: "application/json",
                data: JSON.stringify(data),
                success: function(resp) {
                    $("#modal_edit_client").modal('hide');
                    toastr.success('Updated client successfully');
                     // Refresh the home page (clients page) after updating successfully
                    location.reload();
                },
                error: function(jqXHR, exception) {
                    const responseJson = jQuery.parseJSON(jqXHR.responseText);
                    toastr.error(responseJson['message']);
                }
            });
        }

        // submitHandler
        function submitHandler(form) {
            const formId = $(form).attr('id');
            if (formId === "frm_edit_client") {
                submitEditClient();
            } else if (formId === "frm_email_client") {
                submitEmailClient();
            } else if (formId === "frm_telegram_client") {
                submitTelegramClient();
            }
        }

        $("#modal_email_client").on('show.bs.modal', function (event) {
            let modal = $(this);
            const button = $(event.relatedTarget);
            const client_id = button.data('clientid');
            $.ajax({
                cache: false,
                method: 'GET',
                url: '{{.basePath}}/api/client/' + client_id,
                dataType: 'json',
                contentType: "application/json",
                success: function (resp) {
                    const client = resp.Client;

                    modal.find(".modal-title").text("Send config to client " + client.name);
                    modal.find("#e_client_id").val(client.id);
                    modal.find("#e_client_email").val(client.email);
                },
                error: function (jqXHR, exception) {
                    const responseJson = jQuery.parseJSON(jqXHR.responseText);
                    toastr.error(responseJson['message']);
                }
            });
        });

        $("#modal_qr_client").on('show.bs.modal', function (event) {
            let modal = $(this);
            const button = $(event.relatedTarget);
            const client_id = button.data('clientid');

            modal.find("#qr_client_id").val(client_id);
            regenerateQRCode();
        });

        $("#modal_telegram_client").on('show.bs.modal', function (event) {
            let modal = $(this);
            const button = $(event.relatedTarget);
            const client_id = button.data('clientid');
            $.ajax({
                cache: false,
                method: 'GET',
                url: '{{.basePath}}/api/client/' + client_id,
                dataType: 'json',
                contentType: "application/json",
                success: function (resp) {
                    const client = resp.Client;

                    modal.find(".modal-title").text("Send config to client " + client.name);
                    modal.find("#tg_client_id").val(client.id);
                    modal.find("#tg_client_userid").val(client.telegram_userid);
                },
                error: function (jqXHR, exception) {
                    const responseJson = jQuery.parseJSON(jqXHR.responseText);
                    toastr.error(responseJson['message']);
                }
            });
        });

        $(document).ready(function () {
            $.validator.setDefaults({
                submitHandler: function (form) {
                    submitHandler(form);
                }
            });
            // Edit client form validation
            $("#frm_edit_client").validate({
                rules: {
                    client_name: {
                        required: true,
                    },
                },
                messages: {
                    client_name: {
                        required: "Please enter a name"
                    },
                },
                errorElement: 'span',
                errorPlacement: function (error, element) {
                    error.addClass('invalid-feedback');
                    element.closest('.form-group').append(error);
                },
                highlight: function (element, errorClass, validClass) {
                    $(element).addClass('is-invalid');
                },
                unhighlight: function (element, errorClass, validClass) {
                    $(element).removeClass('is-invalid');
                }
            });
            // Email client form validation
            $("#frm_email_client").validate({
                rules: {
                    e_client_email: {
                        required: true,
                        email: true,
                    },
                },
                messages: {
                    e_client_email: {
                        required: "Please enter an email"
                    },
                },
                errorElement: 'span',
                errorPlacement: function (error, element) {
                    error.addClass('invalid-feedback');
                    element.closest('.form-group').append(error);
                },
                highlight: function (element, errorClass, validClass) {
                    $(element).addClass('is-invalid');
                },
                unhighlight: function (element, errorClass, validClass) {
                    $(element).removeClass('is-invalid');
                }
            });
            // Telegram client form validation
            $("#frm_telegram_client").validate({
                rules: {
                    tg_client_userid: {
                        required: true,
                        number: true,
                    },
                },
                messages: {
                    tg_client_userid: {
                        required: "Please enter a telegram userid",
                        number: "Please enter a valid telegram userid"
                    },
                },
                errorElement: 'span',
                errorPlacement: function (error, element) {
                    error.addClass('invalid-feedback');
                    element.closest('.form-group').append(error);
                },
                highlight: function (element, errorClass, validClass) {
                    $(element).addClass('is-invalid');
                },
                unhighlight: function (element, errorClass, validClass) {
                    $(element).removeClass('is-invalid');
                }
            });
            // 
        });
    </script>
{{end}}
